/*根据ddl 生成 service  mapper controller  plus版本 */

const  {
    firstworldupp,
    toHump,
    firstworlddown,
    toLine
} =require( "./utils");











const {Parser} = require('sql-ddl-to-json-schema');
const lodash =require('lodash')

function createEntity(tableName,cols){
    var tableNameBig=firstworldupp(toHump(tableName))
    var tableNameSmall=firstworlddown(toHump(tableName))
    var colStr=``;
    lodash.map(cols,(define,key)=>{
        var str=`
        /**
        *@description  ${define.description}
        */
        @TableField("${key}")\n
        private ${firstworldupp(define.type)} ${toHump(key)};\n`
        colStr+=str

    })
    const entity=`
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import com.baomidou.mybatisplus.annotation.TableField;



@TableName("${tableNameBig}")
@Data
public class ${tableNameBig}{

    ${colStr}

}
`
    return entity;
}
function createMapper(tableName,cols){
    var tableNameBig=firstworldupp(toHump(tableName))
    var tableNameSmall=firstworlddown(toHump(tableName))
    var colStr=``;
    lodash.map(cols,(define,key)=>{
        var str=`
        /**
        *@description  ${define.description}
        */
        private ${firstworldupp(define.type)} ${toHump(key)};\n\n`
        colStr+=str

    })
    const mapperTemplate=`
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.entity.${tableNameBig};
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface ${tableNameBig}Mapper extends BaseMapper<${tableNameBig}>{
}
`
    return mapperTemplate;
}
function createService(tableName,cols){
    var tableNameBig=firstworldupp(toHump(tableName))
    var tableNameSmall=firstworlddown(toHump(tableName))
    var colStr=``;
    lodash.map(cols,(define,key)=>{
        var str=`
        /**
        *@description  ${define.description}
        */
        private ${firstworldupp(define.type)} ${toHump(key)};\n\n`
        colStr+=str

    })
    const serviceTemplate=`import com.baomidou.mybatisplus.extension.service.IService;
import com.example.demo.entity.${tableNameBig};

import java.util.List;


public interface ${tableNameBig}Service extends IService<${tableNameBig}>{

    /**
     * 查询所有
     * @return
     */
    List<${tableNameBig}> listAll();

\t/**
     * id条件查询
     * @return
     */
    ${tableNameBig} listOne(Long id);

    /***
     * 保存
     * @param user
     * @return
     */
    int insert(${tableNameBig} ${tableNameSmall});

}`
    return serviceTemplate;
}
function createServiceImpl(tableName,cols){
    var tableNameBig=firstworldupp(toHump(tableName))
    var tableNameSmall=firstworlddown(toHump(tableName))
    var colStr=``;
    lodash.map(cols,(define,key)=>{
        var str=`
        /**
        *@description  ${define.description}
        */
        private ${firstworldupp(define.type)} ${toHump(key)};\n\n`
        colStr+=str

    })
    const serviceImpTemplate=`
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.${tableNameBig};
import com.example.demo.mapper.${tableNameBig}Mapper;
import com.example.demo.modules.project.service.${tableNameBig}Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class ${tableNameBig}ServiceImpl extends ServiceImpl<${tableNameBig}Mapper,${tableNameBig}> implements ${tableNameBig}Service{

    @Autowired
    private ${tableNameBig}Mapper ${tableNameSmall}Mapper;

    //查询所有
    @Override
    public List<${tableNameBig}> listAll() {
        List<${tableNameBig}> ${tableNameSmall}s = this.list();
        return ${tableNameSmall}s;
    }

    //条件查询
        @Override
    public ${tableNameBig} listOne(Long id) {
        ${tableNameBig} ${tableNameSmall} = this.getById(id);
        return ${tableNameSmall};
    }

    //保存
        @Override
    public int insert(${tableNameBig} ${tableNameSmall}){
        return ${tableNameSmall}Mapper.insert(${tableNameSmall});

    }

}
`
    return serviceImpTemplate;
}
function createController(tableName,cols){
    var tableNameBig=firstworldupp(toHump(tableName))
    var tableNameSmall=firstworlddown(toHump(tableName))
    var colStr=``;
    lodash.map(cols,(define,key)=>{
        var str=`
        /**
        *@description  ${define.description}
        */
        private ${firstworldupp(define.type)} ${toHump(key)};\n\n`
        colStr+=str

    })
    const controllerTemplate=`
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.dto.PageDto;
import com.example.demo.entity.${tableNameBig};
import com.example.demo.service.${tableNameBig}Service;
import com.example.demo.utils.Lodash;
import com.example.demo.utils.R;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import static com.example.demo.utils.Lodash.isNil;

@RestController
@RequestMapping("/${tableNameSmall}")
public class ${tableNameBig}Controller {

    @Autowired
    private ${tableNameBig}Service ${tableNameSmall}Service;


    @GetMapping("/listAll")
    public R listAll() {
        return R.ok().put("result",${tableNameSmall}Service.list(null));
    }

    @GetMapping("/page")
    @ApiImplicitParams({
            @ApiImplicitParam(name="pageSize",dataType="String"),
            @ApiImplicitParam(name="pageNum",dataType="String")
    })
    public R page(
            Integer pageSize,Integer pageNum) {
        if (isNil(pageSize)) {
            pageSize = 10;
        }
        if (isNil(pageNum)) {
            pageNum = 0;
        }
        QueryWrapper<${tableNameBig}> queryWrapper = new QueryWrapper<>();
        return R.ok().put("result",${tableNameSmall}Service.page(new Page<>(pageNum,pageSize), queryWrapper));
    }
    @PostMapping("/add")
    public R add(@RequestBody ${tableNameBig} ${tableNameSmall}) {
        return R.ok().put("result",${tableNameSmall}Service.save(${tableNameSmall}));
    }
    @PostMapping("/update")
    public R update(@RequestBody  ${tableNameBig} ${tableNameSmall}, HashMap<String, Object> updateOptions) {
        QueryWrapper<${tableNameBig}> queryWrapper=new QueryWrapper<>();
        if(!Lodash.isNil(${tableNameSmall}.getId())){
            queryWrapper.eq("id",${tableNameSmall}.getId());
        }else{
          return R.error("id不能为空");
        }
        return R.ok().put("result",${tableNameSmall}Service.update(${tableNameSmall},queryWrapper));
    }
}
`
    return controllerTemplate;
}
function createVueList(tableName,cols){
    var tableNameBig=firstworldupp(toHump(tableName))
    var tableNameSmall=firstworlddown(toHump(tableName))
    var colStr=``;
    lodash.map(cols,(define,key)=>{
        var str=`
             <el-table-column
            label="${toHump(key)}" prop="${toHump(key)}">
          </el-table-column>
        `
        colStr+=str

    })
    const controllerTemplate=`

<template>
  <div class="app-container" style="padding: 20px;">
    <div>
      <el-button @click="()=>triggerModify()">添加</el-button>
    </div>
    <el-table
      ref="multipleTable"
      :data="lists"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="(rows)=>selectRows=rows">
      <el-table-column
        type="selection"
        width="25">
      </el-table-column>
     ${colStr}
      <el-table-column
        prop="address"
        label="操作"
        fixed="right">
        <template slot-scope="scope">
          <el-button type="text"  @click="()=>triggerModify(scope.row)">修改</el-button>
          <el-button type="text">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="padding: 20px;"
      :page-size="filter.pageSize"
      layout="prev, pager, next"
      :total="filter.total"
      @size-change="(pageSize)=>{$data.filter.pageSize=pageSize;lists=[];ajaxList();}"
      @current-change="(pageNum)=>{$data.filter.pageNum=pageNum;lists=[];ajaxList();}"
    >
    </el-pagination>

    <!--弹出框-->
    <modify class="vue" ref="modifyDialog" @refresh="()=>ajaxList()"></modify>
  </div>
</template>
<script>
  import axios from '@/utils/request'

  export default {
    components: {
      modify: () => import('./modify')
    },
    data() {
      return {
        filter: {
          pageNum: 0,
          pageSize: 10,
          total: 0,
        },
        lists: [],
        selectRows: [],
        showModify: false,
      }
    },
    mounted() {
      this.ajaxList();
    },
    methods: {
      triggerModify() {
        this.$refs['modifyDialog'].init()
      },
      async ajaxList() {
        var _params = {}
        console.log("[get]  /${tableNameSmall}/page")
        console.log('参数', JSON.stringify(_params))
        var result = await axios.get('/${tableNameSmall}/page?pageNum='+this.filter.pageNum+'&&pageSize='+this.filter.pageSize+'', _params).then(res => res.result)
        console.log("结果", result)
        this.lists = result.records
        this.filter.total = Number(result.total)
        this.filter.pageSize = Number(result.size)

      }
    }
  }
</script>



`
    return controllerTemplate;
}
function createVueModify(tableName,cols){
    var tableNameBig=firstworldupp(toHump(tableName))
    var tableNameSmall=firstworlddown(toHump(tableName))
    var colStr=``;
    var formValidateStr=``
    var formStr=``
    lodash.map(cols,(define,key)=>{
        var disabled=(key=='id');
        var str=`
              <el-form-item label="${toHump(key)}" prop="${toHump(key)}" disabled="${disabled}">
          <el-input v-model="form.${toHump(key)}" :disabled="${disabled}"></el-input>
        </el-form-item>
        `
        var str1=`
           ${toHump(key)}: [{required: true, trigger: 'blur',message:"${toHump(key)}不能为空"}],
        `
        var str2=`${toHump(key)}:"",`
        colStr+=str;
        formValidateStr+=str1;
        formStr+=str2;

    })
    const controllerTemplate=`

<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="30%"
    :before-close="handleClose">
    <div>
      <el-form
        :rules="loginRules"
        ref="form" :model="form" label-width="80px">
${colStr}
       
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="()=>{
   submit()
    }">确 定</el-button>
  </span>
  </el-dialog>

</template>
<script>
  import axios from '@/utils/request'

  export default {
    data() {
      return {
        title: "管理",
        dialogVisible: false,
        form: {${formStr}},
        loginRules: {
         ${formValidateStr}
        },
      }
    },
    methods: {
      handleClose() {
      },
      init(_data) {
        if (_data && _data.id) {
          this.title = "修改"
        } else {
          this.title = "添加"
        }
        this.dialogVisible = true
        this.form = _data ? _data : {}
      },
      async submit() {
        this.$refs['form'].validate(async (isyes) => {
          if (isyes) {
            var _params = this.form
            console.log("[get]  /${tableNameSmall}/add")
            console.log('参数', JSON.stringify(_params))
            var url=this.form.id?'/${tableNameSmall}/update':'/${tableNameSmall}/add'
            var result = await axios.post(url, _params).then(res => res.data)
            console.log("结果", result)
            this.dialogVisible = false;
            this.$emit('refresh')
          }
        })
      }
    }
  }
</script>




`
    return controllerTemplate;
}
function createJsJson(tableName,cols){
    var tableNameBig=firstworldupp(toHump(tableName))
    var tableNameSmall=firstworlddown(toHump(tableName))
    var colStr=``;
    var formValidateStr=``
    var formStr=``
    lodash.map(cols,(define,key)=>{
        var disabled=(key=='id');
        var str=`${toHump(key)}: "",  //${define.description}
       `
        colStr+=str;

    })
    const controllerTemplate=`
{${colStr}}
`
    return controllerTemplate;
}


function createTemplate(ddlStr) {
    const parser = new Parser('mysql');
   /* CREATE TABLE `match_activity_pair` (
        `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
        `peroid` int(10) DEFAULT NULL COMMENT '周期（洽谈时间）',
        `order` int(10) DEFAULT NULL COMMENT '顺序',
        `startTime` datetime DEFAULT NULL COMMENT '开始洽谈时间',
        `endTime` datetime DEFAULT NULL COMMENT '结束洽谈时间',
        `demandId` bigint(20) DEFAULT NULL COMMENT '需求id',
        `meetingId` bigint(20) DEFAULT NULL COMMENT '会议id',
        `supplierId` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '供应商id',
        `purchaserId` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '采购商id',
        `activityId` bigint(20) DEFAULT NULL COMMENT '商贸活动id',
        `sponsor` int(1) DEFAULT NULL COMMENT '0:供应商发起(pc) 1:采购商发起(主办后台)',
        `status` int(1) DEFAULT '0' COMMENT '预约状态 0:待确认 1:已确认 2:被拒绝 3:已取消',
        `projectId` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '活动id',
        `isStart` int(1) DEFAULT '2' COMMENT '会议状态标识 1：开始 0：结束 2 未开始',
        PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=442 DEFAULT CHARSET=utf8;*/

    const jsonSchemaDocuments = parser.feed(ddlStr+";")
        .toJsonSchemaArray({});
    var json=jsonSchemaDocuments[0]
    var tableName=json.title
    var definitions=json.definitions
    var keys=[]
    const entityResult=createEntity(tableName,definitions)
    const mapperResult=createMapper(tableName,definitions)
    // console.log("entityResult",entityResult)
    return {
        entity:entityResult,
        mapper:mapperResult,
        service:createService(tableName,definitions),
        serviceImpl:createServiceImpl(tableName,definitions),
        controller:createController(tableName,definitions),
        vuelist:createVueList(tableName,definitions),
        vuemodify:createVueModify(tableName,definitions),
        jsjson:createJsJson(tableName,definitions)
    }

}

module.exports=createTemplate